package list;

/**
 * 树一般用二分递归
 *
 */
public class 有序链表转换二叉搜索树_109 {
    public TreeNode sortedListToBST(ListNode head) {
        if (head == null) return null;
        if (head.next == null) return new TreeNode(head.val);
        ListNode fast = head, slow = head, preSlow = null;
        // 快慢指针找中点
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            preSlow = slow;
            slow = slow.next;

        }
        preSlow.next = null; // 不断开 下次还会找到这次的root  无限循环
        TreeNode root = new TreeNode(slow.val);
        root.left = sortedListToBST(head);   // 递归法
        root.right = sortedListToBST(slow.next);
        return root;

    }

}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}